package org.thirdHero.db.service;

import org.thirdHero.db.dao.SysRelationMapper;
import org.thirdHero.db.domain.SysRelation;
import org.thirdHero.db.domain.SysRelationExample;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SysRelationService {
    @Resource
    SysRelationMapper sysRelationMapper;

    public List<SysRelation> queryRelationByRoleId(Integer roleId){
        SysRelationExample sysRelationExample = findRelationByRoleId(roleId);
        return this.sysRelationMapper.selectByExample(sysRelationExample);
    }

    private SysRelationExample findRelationByRoleId(Integer roleId) {
        SysRelationExample sysRelationExample = new SysRelationExample();
        SysRelationExample.Criteria criteria = sysRelationExample.createCriteria();
        criteria.andRoleidEqualTo(roleId);
        return sysRelationExample;
    }

    public void saveRelation(Integer roleId,String relationIds){
        deleteRelationByRoleId(roleId);
        String[] relationIdArr = relationIds.split(",");
        for(int i = 0; i < relationIdArr.length ;i++){
            String menuid = relationIdArr[i];
            SysRelation relation = new SysRelation();
            relation.setMenuid(Integer.parseInt(menuid));
            relation.setRoleid(roleId);
            saveRelation(relation);
        }
    }
    public int deleteRelationByRoleId(Integer roleId){
        SysRelationExample relationByRoleExample = this.findRelationByRoleId(roleId);
        return this.sysRelationMapper.deleteByExample(relationByRoleExample);
    }
    public int saveRelation(SysRelation sysRelation){
      return  this.sysRelationMapper.insert(sysRelation);
    }
}
